const { execSync } = require("child_process");
const path = require("path");
const fs = require("fs");
const { dialog } = require("electron").remote;
const os = require("os");
const dataPath = `C:/Users/${
  os.userInfo().username
}/AppData/Roaming/easyWebsite/developPageImage`;

function packPage(tree, that) {
  let aimPath;
  try {
    //写入网站代码
    fs.writeFileSync(
      path.join(__dirname, "../../website_template/src/App.vue"),
      `<script>
      export default {
        name: "App",
        data() {
          return {
            tree: ${tree},
            pageName: "index", //页面名称
          };
        },
        methods: {},
        render(h) {
          return <div>{this.$explain(this, h, this.tree[this.pageName])}</div>;
        },
      };
      </script>
      `
    );

    //进行打包
    execSync(
      `cd ${path.join(__dirname, "../../website_template")} && npm run build`
    );

    //选择存放目录
    aimPath = dialog.showOpenDialogSync({
      title: "请选择要存放的目录",
      properties: ["openFile", "openDirectory"],
    });
    if (aimPath == undefined) {
      that.$message({
        message: "请选择要存放的目录",
        type: "warning",
      });
    }

    if (aimPath == undefined) return 400;

    //复制源码
    /**
     * /y：不弹出“确认是否覆写已存在目标文件”的提示
     * /e：复制文件及子文件夹内所有内容，包括空文件夹（对比/s, /s不复制空文件夹）
     * /i：如果b不存在并且复制超过一个文件则默认b是目录名
     * /q：quiet，静默模式
     */
    execSync(
      `xcopy ${path.join(__dirname, "../../website_template/dist")} ${path.join(
        aimPath[0],
        "./dist"
      )} /y /e /i /q`
    );
    //复制图片
    execSync(
      `xcopy ${path.join(dataPath)} ${path.join(
        aimPath[0],
        "./dist/img"
      )} /y /e /i /q`
    );

    return 200;
  } catch (error) {
    console.error(error);
    return 500;
  }
}

module.exports = { packPage };
